import list1 from './img/list1.jpeg';
import list2 from './img/list2.jpeg';
import list3 from './img/list3.jpeg';

let listArr = [list1, list2, list3];
//面向对象
// 定义一个红绿色类(构造函数)

function Light($box) {
  //装红绿灯的容器
  this.box = document.querySelector($box);
  //初始值
}
Light.prototype = {
  constructor: Light,
  //初始化图片方法 顺序从上到下
  init: function () {
    this.index = 1;
    // 调用创建图片标签
    this.render();
  },
  // 把img节点添加到box中
  render: function () {
    this.img = new Image();
    //设置图片不可拖拽 HTML自带属性
    this.img.draggable = false;
    //设置图片路径
    this.img.src = `${listArr[this.index - 1]}`;
    //添加到box中
    this.box.appendChild(this.img);
  },
  // 初始化图片方法 顺序从下到上
  reseverFn: function () {
    this.index = 3;
    this.render();
    this.prevBindClick();
  },
  // 点击下一张
  bindClick: function () {
    this.img.addEventListener('click', () => {
      console.log('下一张', this.index);
      this.nextFn();
    });
  },
  //点击上一张
  prevBindClick: function () {
    this.img.addEventListener('click', () => {
      console.log('上一张', this.index);
      this.prevFn();
    });
  },
  nextFn: function () {
    this.index++;
    //判断图片是否超出范围1-3
    this.index > 3 && (this.index = 1);
    //修改图片路径
    this.img.src = `${listArr[this.index - 1]}`;
  },
  prevFn: function () {
    this.index--;
    //判断图片是否超出范围1-3
    if (this.index < 1) {
      this.index = 3;
    }
    //修改图片路径
    this.img.src = `${listArr[this.index - 1]}`;
  },
  // 自动播放
  autoPlay: function () {
    this.timer = setInterval(() => {
      this.nextFn();
    }, 1000);
  },
  //鼠标进入停止播放
  stopPlay: function () {
    this.img.addEventListener('mouseenter', () => {
      clearInterval(this.timer);
    });
  },
  //鼠标离开继续播放
  leavePlay: function () {
    this.img.addEventListener('mouseleave', () => {
      this.autoPlay();
    });
  },
};

// 顺序上-下
let l1 = new Light('.box1');
l1.init();
l1.bindClick();
//自动播放上-下(可控的，鼠标移入就不能播放，松开自动播放)
let l2 = new Light('.box2');
l2.init();
l2.autoPlay();
l2.stopPlay();
l2.leavePlay();
//顺序下-上
let l3 = new Light('.box3');
l3.reseverFn();
